//
//  KDVPNStore.m
//  KDExample
//
//  Created by YeQing on 2017/3/8.
//  Copyright © 2017年 naruto. All rights reserved.
//

#import "KDVPNStore.h"
#import <NetworkExtension/NetworkExtension.h>

@interface KDVPNStore()

@end

@implementation KDVPNStore
#pragma mark - system
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self configVPN];
    }
    return self;
}

#pragma mark - 连接vpn
- (void)startVPN
{
//    [[NEVPNManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError *error){
//        if(error){
//            return ;
//        }
//        NSError *startError = nil;;
//        [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];
//        if(startError) {
//            BCLog(@"Start error: %@", startError.localizedDescription);
//        }
//        else {
//            BCLog(@"Connection established!");
//        }
//    }];
}

#pragma mark - 断开vpn
- (void)stopVPN
{
//    [[NETunnelProviderManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
//        [[NETunnelProviderManager sharedManager].connection stopVPNTunnel];
//    }];
//    [[NEVPNManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError *error){
//        if(error){
//            return ;
//        }
//        [[NEVPNManager sharedManager].connection stopVPNTunnel];
//    }];
}
#pragma mark - 删除配置
- (void)removeVPN
{
    [[NEVPNManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError *error){
        if (error){
            return ;
        }
        [[NEVPNManager sharedManager] removeFromPreferencesWithCompletionHandler:^(NSError *error){
            if(error){
                BCLog(@"Remove error: %@", error);
            }
            else{
                BCLog(@"Remove success");
            }
        }];
    }];
}

#pragma mark - 配置vpn
- (void)configVPN
{
//    [[NEVPNManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError *error) {
//        if(error) {
//            BCLog(@"Load error: %@", error);
//        }
//        else {
////            NETunnelProviderManager
//            // No errors
//            NEVPNProtocolIKEv2 *protocol = [[NEVPNProtocolIKEv2 alloc] init];
//            protocol.serverAddress = KDVPN_Server;
//            protocol.username = @"username";
//            //先保存密码到keychain
//            [self createKeychainValue:@"password" forIdentifier:@"VPN_PASSWORD"];
//            protocol.passwordReference = [self searchKeychainCopyMatching:@"VPN_PASSWORD"];
////            NEVPNIKEAuthenticationMethodNone：不对IPSec服务器进行认证
////            NEVPNIKEAuthenticationMethodCertificate：使用证书和私钥进行认证
////            NEVPNIKEAuthenticationMethodSharedSecret：使用共享密钥进行认证
//            protocol.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
//            //                protocol.sharedSecretReference = [VPN server shared secret from keychain];
//            protocol.localIdentifier = @"didi-vpn";
//            protocol.remoteIdentifier = @"[VPN remote identifier]";
//            protocol.useExtendedAuthentication = YES;
//            protocol.disconnectOnSleep = NO;
//            //                protocol.identityData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"clientCert" ofType:@"p12"]];
//            [[NEVPNManager sharedManager] setProtocol:protocol];
//            //禁止为了省电自动断开,开启按需连接
//            [[NEVPNManager sharedManager] setOnDemandEnabled:NO];
//            [[NEVPNManager sharedManager] setLocalizedDescription:@"滴滴codevpn"];
//            //设置按需策略（NEOnDemandRuleConnect：网络连接自动连接vpn）
//            NSMutableArray *rules = [[NSMutableArray alloc] init];
//            NEOnDemandRuleConnect *connectRule = [NEOnDemandRuleConnect new];
//            [rules addObject:connectRule];
//            [[NEVPNManager sharedManager] setOnDemandRules:rules];
//            [[NEVPNManager sharedManager] setEnabled:YES];
//            [[NEVPNManager sharedManager] saveToPreferencesWithCompletionHandler:^(NSError *error) {
//                if(error) {
//                    BCLog(@"Save error: %@", error);
//                }
//                else {
//                    BCLog(@"Saved!");
//                }
//            }];
//        }
//    }];
}


#pragma mark - KeyChain

static NSString * const serviceName = @"im.zorro.ipsec_demo.vpn_config";

- (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier
{
    
    NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];
    
    [searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    
    NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
    
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
    
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
    
    [searchDictionary setObject:serviceName forKey:(__bridge id)kSecAttrService];
    
    return searchDictionary;
    
}

- (NSData *)searchKeychainCopyMatching:(NSString *)identifier
{
    
    NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];
    
    // Add search attributes
    
    [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    
    // Add search return types
    
    // Must be persistent ref !!!!
    
    [searchDictionary setObject:@YES forKey:(__bridge id)kSecReturnPersistentRef];
    
    CFTypeRef result = NULL;
    
    SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result);
    
    return (__bridge_transfer NSData *)result;
    
}

- (BOOL)createKeychainValue:(NSString *)password forIdentifier:(NSString *)identifier
{
    
    NSMutableDictionary *dictionary = [self newSearchDictionary:identifier];
    
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)dictionary);
    
    NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
    
    [dictionary setObject:passwordData forKey:(__bridge id)kSecValueData];
    
    status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
    
    if (status == errSecSuccess) {
        
        return YES;
        
    }
    
    return NO;
    
}
@end
